<template>
  <view class="search">
    <view class="top">
      <view class="t">
        <view class="s">
          <button type="default" plain size="mini" @click="goBack">返回</button>
        </view>
        <uni-search-bar @confirm="search" v-model="info.keyword" @cancel="cancel"></uni-search-bar>
      </view>
    </view>
    <view class="content">
      <view class="search-user" v-if="info.searchUser.length != 0">
        <view class="title">用户</view>
        <view class="list user" v-for="(item, index) in info.searchUser" :key="item.id">
          <image :src="item.imgurl" mode=""></image>
          <view class="name" @click="gotoUserhome(item)">
            <span v-html="item.username"></span>
            <span v-html="item.email"></span>
          </view>
          <view class="right">
            <button type="primary" size="mini" :class="item.flag ? 'send' : 'add'" @click="changeRouter(item)">
              {{item.flag ? '发消息' : '加好友' }}
            </button>
          </view>
        </view>
      </view>
    </view>
    <view class="no" v-if="info.keyword == ''">
      <uni-icons type="search" size="100"></uni-icons>
      <view class="no-text">
        <span>快来搜索吧~</span>
      </view>
    </view>
    <view class="no" v-if="info.keyword != '' && info.searchUser.length == 0">
      <uni-icons type="info" size="100"></uni-icons>
      <view class="no-text">
        <span>没有搜索到相关信息哦~</span>
      </view>
    </view>

  </view>
</template>

<script setup>
  import _ from 'lodash'
  import {
    reactive,
    watch,
    getCurrentInstance
  } from 'vue'
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    useUserStore
  } from '@/store/user.js'
  import {
    requestNet
  } from '@/api/base.js'
  const user = useUserStore()
  const instance = getCurrentInstance()
  const info = reactive({
    keyword: '', //搜索关键字
    userInfo: {}, //当前用户信息
    token: '',
    searchUser: [], //符合搜索信息的用户列表

  })
  //判断是否是好友
  function isFirend(item) {
    let flag = 0;
    requestNet({
      url: '/search/checkfriend',
      data: {
        uid: info.userInfo.userid,
        fid: item.userid
      },
      header: {
        token: info.token
      }
    }).then(res => {
      if (res.data.code == 200) {
        flag = 1
        item.flag = flag
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
  }

  //搜索好友
  function search(val) {
    let {
      value
    } = val
    if (value == '') {
      uni.showToast({
        title: '输入不能为空',
        icon: 'error'
      });
      return;
    }
    //向后端请求数据
    requestNet({
      url: '/search/user',
      data: {
        keyword: value,
        uid: info.userInfo.userid
      },
      header: {
        token: info.token,
      }
    }).then(data => {
      if (data.data.code == 200) {
        let arr = data.data.data
        let reg = new RegExp(value, 'g');
        for (let i = 0; i < arr.length; i++) {
          isFirend(arr[i]) //判断是否是好友
          if (arr[i].username.replace(reg, "<span style='color:#4AAAFF;'>" + value + "</span>") != arr[i]
            .username) {
            arr[i].username = arr[i].username.replace(reg, "<span style='color:#4AAAFF;'>" + value + "</span>")
            arr[i].imgurl = instance.proxy.serverUrl + arr[i].imgurl //处理图片路径
            continue
          } else if (arr[i].email.replace(reg, "<span style='color:#4AAAFF;'>" + value + "</span>") != arr[i]
            .email) {
            arr[i].email = arr[i].email.replace(reg, "<span style='color:#4AAAFF;'>" + value + "</span>");
            arr[i].imgurl = instance.proxy.serverUrl + arr[i].imgurl
            continue
          }

        }
        info.searchUser = arr
      } else if (data.data.code == 400) {
        uni.showToast({
          title: data.data.message,
          icon: 'error'
        })
      }
    }).catch(err => {
      uni.showToast({
        title: err,
        icon: 'error'
      })
    })
    // let temp = [];
    // //深拷贝解决共享一份内存地址的问题 ，不影响原数组！！！
    // temp = _.cloneDeep(info.userlist.filter(item => {
    //   isFirend(item)
    //   return item.name.search(value) != -1 || item.email.search(value) != -1
    // }))
  }

  //获取缓存登录用户数据
  function getUserInfo() {
    info.userInfo = user.userinfo
    info.token = user.token
  }
  //跳转路由
  function changeRouter(item) {
    if (item.flag) {
      uni.navigateTo({
        url: `/pages/chatPage/chatPage?id=${item.userid}`
      })
    } else uni.navigateTo({
      url: `/pages/reqfirend/reqfirend?id=${item.userid}`
    })
  }

  function cancel() {
    info.keyword = ''
    info.searchUser = []
  }
  //前往用户主页
  function gotoUserhome(item) {
    uni.navigateTo({
      url: `/pages/reqfirend/reqfirend?id=${item.userid}`
    })
  }

  //返回上一页面
  function goBack() {
    uni.navigateTo({
      url: '/pages/home/home'
    })
  }
  //监听关键词变化
  watch(() => info.keyword, () => {
    if (info.keyword == '')
      info.searchUser = []
  })
  onLoad(() => {
    // getFirendListBy()
    // getUser1FirendBy()
    getUserInfo() //获取当前登录用户的信息
  })
</script>

<style lang="scss" scoped>
  @import '@/assets/css/top.scss';

  .search {
    .top {
      display: block;
      justify-content: center;

      .t {
        display: flex;
        width: 750rpx;
        justify-content: space-around;
        align-items: center;

        .s {
          margin-left: 20rpx;
        }
      }
    }
  }

  .search-user {
    margin: 30rpx;

    .title {
      font-size: 44rpx;
      font-weight: 700;
      margin-bottom: 20rpx;
    }

    .list {
      position: relative;
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;

      image {
        height: 80rpx;
        width: 80rpx;
        margin-right: 20rpx;
      }

      .name {
        font-size: 32rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }

      span:nth-child(2) {
        margin-top: 10rpx;
        font-size: 24rpx;
      }

      .right {
        position: absolute;
        right: 0;

        .add {
          border: none;
          background: #FFE431;
          // border-radius: 12px;
          color: #272832;
        }

        .send {
          // background: var(--van-button-primary-background);
          background: rgba(74, 170, 255, 0.10);
          // opacity: 0.2;
          color: #4AAAFF;
          border: none;
        }
      }

    }


  }

  .no {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    margin-top: 200rpx;
    opacity: 0.5;

    &-text {
      display: block;
      font-size: 36rpx;
      margin-top: 20rpx;
    }
  }

  .uni-searchbar[data-v-180dbe05] {
    width: 510rpx;
  }

  image {
    border-radius: 10px;
  }
</style>
